<template>
  <div>
    <div style="margin-bottom: 15px;">
      <!-- 顶部添加数据 -->
      <span>客户姓名：</span>
      <el-input v-model="params.cname" style="width: 150px; margin-right: 15px;" placeholder="请输入客户姓名"></el-input>
      <span>手机号码：</span>
      <el-input v-model="params.phone" style="width: 150px; margin-left: 5px;" placeholder="请输入手机号码"></el-input>
      <el-button type="warning" style="margin-left: 10px;" @click='searchCustomer()'>查询</el-button>
      <el-button type="warning" style="margin-left: 10px;" @click='reset()'>清空</el-button>
      <el-button type="primary" style="margin-left: 10px;" @click='insert()'>新增</el-button>
       <el-upload
        action=""
        :show-file-list="false"
        :before-upload="beforeUpload"
        :http-request="importData"
        accept=".xlsx, .xls"
        style="display: inline-block; margin-left: 10px;">
        <el-button type="success">导入</el-button>
      </el-upload>
      <el-button type="success" style="margin-left: 10px;" @click='exportData'>导出</el-button>
    </div>

    <div>
      <!-- 引入表格 -->
      <el-table
        :data="tableData"
        :border="true"
        max-height="600">
        style="width: 100%">
        <!-- 表格内容 -->
        <el-table-column fixed prop="cno" label="客户编号" width="100"></el-table-column>
        <el-table-column prop="cname" label="客户姓名" width="130"></el-table-column>
        <el-table-column prop="gender" label="性别" width="100"></el-table-column>
        <el-table-column prop="age" label="年龄" width="100"></el-table-column>
        <el-table-column prop="phone" label="电话号码" width="200"></el-table-column>
        <el-table-column prop="address" label="居住地址" width="300"></el-table-column>
        <el-table-column  label="操作" width="200">
          <template slot-scope="scope">
            <el-button type="primary" @click="edit(scope.row)">编辑</el-button>
            <el-popconfirm title="确定删除吗？" @confirm="del(scope.row.cno)">
                <el-button slot="reference" type="danger" style="margin-left: 5px;">删除</el-button>
              </el-popconfirm>
          </template>
          
          
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页显示 -->
      <div>
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="params.pageNum"
          :page-sizes="[5, 10, 15, 20]" 
          :page-size="params.pageSize"
          layout="total, sizes, prev, pager, next"
          :total="total">
        </el-pagination>
      </div>

      <!-- 对话框 -->
       <div>
          <el-dialog title="请填写信息" :visible.sync="dialogFormVisible" width='40%'>
          <el-form :model="form">
            <el-form-item label="客户姓名" label-width= "15%">
              <el-input v-model="form.cname" autocomplete="off" style="width:90%"></el-input>
            </el-form-item>
            <el-form-item label="客户性别" label-width= "15%">
              <el-radio v-model="form.gender" label="男" >男</el-radio>
              <el-radio v-model="form.gender" label="女" >女</el-radio>
            </el-form-item>
            <el-form-item label="客户年龄" label-width= "15%">
              <el-input v-model="form.age" autocomplete="off" style="width:90%"></el-input>
            </el-form-item>
            <el-form-item label="手机号码" label-width= "15%">
              <el-input v-model="form.phone" autocomplete="off" style="width:90%"></el-input>
            </el-form-item>
            <el-form-item label="居住地址" label-width= "15%">
              <el-input v-model="form.address" autocomplete="off" style="width:90%"></el-input>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button type="primary" @click='submit()'>确定</el-button>
          </div>
          </el-dialog>
        </div>

        <el-dialog
          title="导入结果"
          :visible.sync="importResultVisible"
          width="30%">
          <div>{{ importResultMessage }}</div>
          <span slot="footer" class="dialog-footer">
            <el-button type="primary" @click="importResultVisible = false">确定</el-button>
          </span>
        </el-dialog>
  </div>
</template>

<script>
import request from '@/utils/request'


  export default {
    data() {
      return {
        params: {
          cname: '',
          phone: '',
          pageNum: 1,
          pageSize: 10
        },
        total:0,
        form:{},
        dialogFormVisible: false,
        tableData: [],
        importResultVisible: false,
        importResultMessage: '',
      }
    },

    // 页面加载时，在created中做一些事情
    created() {
      this.searchCustomer();
    },
    
    // 定义一些页面上控件触发的方法
    methods: {
      // 通过姓名和手机号码查询内容
      searchCustomer() {
        request.get("/customer/searchCustomer", {
          params: this.params
        }).then(res => {
          if (res.code === '0') {
            this.tableData = res.data.list;
            this.total = res.data.total;
          } else {
            this.$message({
              message: res.msg,
              type: 'error'
            });
          }
        })
      },

      // 清空输入空内容 --> 查询所有
      reset() {
        this.params = {
          cname: '',
          phone: '',
          pageNum: 1,
          pageSize: 10
        }
        this.searchCustomer();
      },

      // 显示出对话框
      insert() {
        this.form = {};
        this.dialogFormVisible = true;
      },
      
      // 编辑内容，用于更新
      edit(obj) {
        this.form = obj;
        this.dialogFormVisible = true;
      },

      // 提交插入的内容
      submit() {
        request.post("/customer/insert", this.form).then(res => {
          if (res.code === '0') {
            this.$message({
              message: '操作成功',
              type: 'success'
            });
            this.dialogFormVisible = false;
            this.searchCustomer();
          } else {
            this.$message({
              message: res.msg,
              type: 'error'
            });
          }
        })
      },

      // 删除内容
      del(cno) {
        request.delete("/customer/delete/" + cno).then(res => {
          if (res.code === '0') {
            this.$message({
              message: '删除成功',
              type: 'success'
            });
            this.searchCustomer();
            this.tableData = this.tableData.filter(item => item.cno !== cno);
            this.total -= 1;  
          } else {
            this.$message({
              message: res.msg,
              type: 'error'
            });
          }
        })
      },      

      exportData() {
      const queryParams = {
        cname: this.params.cname,
        phone: this.params.phone
      };
      
       request.get("/customer/export", {
        params: queryParams, // 只传递查询条件
        responseType: 'blob'
      }).then(res => {
        // 创建Blob对象
        const blob = new Blob([res], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        
        // 设置文件名
        const fileName = `客户数据_${new Date().toLocaleDateString().replace(/\//g, '-')}.xlsx`;
        link.setAttribute('download', fileName);
        
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);
        
        this.$message.success('导出成功');
      }).catch(error => {
        console.error('导出失败', error);
        this.$message.error('导出失败: ' + (error.message || '请检查网络连接'));
      });
    },
    
    // 导入前检查
    beforeUpload(file) {
      const isExcel = file.type === 'application/vnd.ms-excel' || 
                     file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
      const isLt10M = file.size / 1024 / 1024 < 10;
      
      if (!isExcel) {
        this.$message.error('只能上传Excel文件!');
      }
      if (!isLt10M) {
        this.$message.error('文件大小不能超过10MB!');
      }
      
      return isExcel && isLt10M;
    },
    
    // 导入数据
     importData(options) {
      const file = options.file;
      const formData = new FormData();
      formData.append('file', file);
      
      // 使用封装的request而不是axios
      request.post("/customer/import", formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }).then(res => {
        if (res.code === '0') {
          this.importResultMessage = res.msg || '导入成功';
          this.importResultVisible = true;
          this.searchCustomer(); // 刷新数据
        } else {
          this.$message.error(res.msg || '导入失败');
        }
      }).catch(error => {
        console.error('导入失败', error);
        this.$message.error('导入失败: ' + (error.message || '服务器错误'));
      });
    },

      // 每页条数改变触发
      handleSizeChange(pageSize) {
        // 改变每页显示条数
        this.params.pageSize = pageSize; 
        // 再做一次查询
        this.searchCustomer();
      },

      // 页码改变触发
      handleCurrentChange(currentPage) {
        this.params.pageNum = currentPage;
        this.searchCustomer();
      },

    }
  }

</script>